package com.nmsl.system.service.impl;


import com.alibaba.fastjson2.JSONObject;


import com.nmsl.system.Utils.HttpClientUtil;
import com.nmsl.system.domain.User;
import com.nmsl.system.domain.UserLoginDTO;
import com.nmsl.system.domain.WeChatProperties;
import com.nmsl.system.mapper.UserMapper;
import com.nmsl.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service

public class UserServiceImpl implements IUserService {
    //微信服务接口地址
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    //wexin配置类
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    //微信登陆
    @Override
    public User wxlogin(UserLoginDTO userLoginDTO) {
        //调用微信接口服务，获得当前用户的openId
        String openid = getOpenid(userLoginDTO.getCode());
        //判断是否为为空，如果为空则登录失败，抛出异常
        if (openid == null){
            throw new RuntimeException("登录失败");
        }
        //判断是否为新用户（看openId是否在用户表），新用户自动完成注册
        User user = userMapper.getByOpenid(openid);
        if (user == null){
            user = User.builder()
                    .name(userLoginDTO.getNickName())
                    .avatar(userLoginDTO.getAvatarUrl())
                    .phone(userLoginDTO.getPhone())
                    .nickName("小程序用户")
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        //返回用户对象
        return user;
    }

    //写个方法方便直接调用，不用每次都去写微信服务获取openid
    private String getOpenid(String code){
        //调用微信接口服务，获得当前用户的openId
        Map<String, String> map = new HashMap<>();//封装请求参数
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String s = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSONObject.parseObject(s);//将返回的json字符串转换为json对象
        return jsonObject.getString("openid");//返回openid
    }
}
